package com.smt.modules.bus.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.smt.common.enums.Code;
import com.smt.common.enums.EventEnum;
import com.smt.common.utils.*;
import com.smt.modules.bus.dao.InviteDao;
import com.smt.modules.bus.entity.*;
import com.smt.modules.bus.service.*;
import com.smt.modules.bus.vo.request.JoinInvitesReq;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 邀请用户实现(限制邮箱邀请) TODO
 *
 * @author zhangyi
 * @date 2018/10/16 11:44
 */
@Service
public class InviteServiceImpl extends ServiceImpl<InviteDao, InviteEntity> implements InviteService {
    @Autowired
    private EmailUtil emailUtil;

    @Autowired
    private TeamService teamService;

    @Autowired
    private MemberUserService memberUserService;

    @Autowired
    private EventService eventService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private CompanyService companyService;

    @Value("${localhost.url}")
    private String url;

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @Autowired
    private AddressBookService addressBookService;
    /**
     * 邀请用户 TODO
     *
     * @param projectId        当前项目id
     * @param type             0 邀请内部还是 1 外部的
     * @param memberUserEntity 当前操作邀请的用户
     * @param contact          被邀请的人的连接方式
     * @param teamId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R sendInvite(Integer type, String contact, MemberUserEntity memberUserEntity, Long projectId, Long teamId) {
        Long userId = memberUserEntity.getUserId();
        String fromUser = memberUserEntity.getMobile() == null ?
                memberUserEntity.getEmail() : memberUserEntity.getMobile();
        //存入缓存或者数据库 用户短信用户验证
        //redis
        ProjectEntity projectEntity = projectService.selectById(projectId);
        String projectName = projectEntity.getProjectName();
        //邀请内部员工 确认邀请直接加入该公司
        //发送邮件信息
        boolean isEmail = CheckUtil.checkEmail(contact);
        boolean isPhone = CheckUtil.checkPhone(contact);
        CompanyEntity companyEntity = null;
        Map<String, Object> map = new ConcurrentHashMap<>();
        map.put("toName", contact);
        map.put("formName", fromUser);
        if(isEmail) {
            //添加邀请人记录
            AddressBookEntity addressBookEntity = new AddressBookEntity(userId, contact, DateTime.now().toDate(),projectId);
            int count = addressBookService.selectCount(new EntityWrapper<AddressBookEntity>()
                    .eq("member_id", userId)
                    .eq("email_contact", contact)
                    .eq("is_delete", 0));
            if (count == 0) {
                addressBookService.insert(addressBookEntity);
            }
        }
        if (type.equals(0)) {
            //查找的是该用户创建的公司
            companyEntity = companyService.selectOne(new EntityWrapper<CompanyEntity>()
                    .eq("member_id", userId));
            //填充邮件模板信息
            map.put("company", null != companyEntity ? companyEntity.getCompanyName() : " ");
            map.put("project", projectName == null ? "风信子平台" : projectName);

            //查询本地用户记录
            EntityWrapper<MemberUserEntity> entityEntityWrapper = new EntityWrapper<>();
            if (isEmail) {
                map.put("url", url + "?formUser=" + fromUser + "&t=" + teamId);
                emailUtil.sendMail(contact, "您的邀请信", map, "invite.html");
                entityEntityWrapper.eq("email", contact);
            } else if (isPhone) {
                //后期手机
            } else {
                return R.error(4, "用户联系方式错误");
            }
            MemberUserEntity emailUser = memberUserService.selectOne(new EntityWrapper<MemberUserEntity>()
                    .eq("email", contact));
            if(!Objects.isNull(emailUser)){
                List<TeamEntity> teamListMember = teamService.selectList(new EntityWrapper<TeamEntity>()
                        .eq("member_id", emailUser.getUserId())
                        .eq("project_id",projectId)
                        .eq("member_exist",0));
                for(TeamEntity t : teamListMember){
                    Long id = t.getBusTeamId();
                    if (id.equals(teamId)) {
                        return R.error(6, "不可邀请本公司的成员");
                    }
                }
            }
            boolean isInsert = false;
            //添加手机联系方式
            MemberUserEntity toUserEntity = memberUserService.selectOne(entityEntityWrapper);
            InviteEntity inviteEntity = new InviteEntity(teamId, contact, fromUser, 0, DateTime.now().toDate());
            if(toUserEntity != null) {
                //获取用户的手机联系方式（未注册用户，保存为空）注册的时候查找其邀请信息
                inviteEntity.setToUserContact(toUserEntity.getMobile());
            }
            isInsert = insert(inviteEntity);
            return isInsert ? R.ok("发送用户邀请信成功") : R.error(8, "邀请该用户失败");
        } else {
            //邀请外部员工 引导其注册登录(推荐该平台，发送平台介绍)
            map.put("url", url);
            emailUtil.sendMail(contact, "易树风信子邀您体验", map, "propaganda.html");
        }
        return R.ok("邀请邮件发送成功，请等待用户确认");
    }

    /**
     * 确认邀请信息 TODO
     * <p>
     * 当用户在平台上有信息的时候，可以直接将用户关系连接到团队上
     * 要是用户没有信息的时候，引导他注册登录，需要在在数据库中保存一张邀请记录的表，
     * 然后在数据库表中查询该用户是否是被邀请过来的，还是自动登录的，如果是邀请过来的，
     * 是否点击邀请状态，等等，然后根据其操作，执行相应的动作。
     * <p>
     * 点击完成后返回首页地址
     *
     * @param contact
     * @param type    1 确认 2 拒绝
     * @param formUser
     * @param tId
     * @param iId
     * @return
     */
    @Override
    public R enterInvite(String contact, Integer type, String formUser, Long tId,Long iId) {
        //获取其联系方式
        EntityWrapper<MemberUserEntity> ew = new EntityWrapper<>();
        MemberUserEntity memberUserEntity = null;
        boolean isPhone = CheckUtil.checkPhone(contact);
        boolean isEmail = CheckUtil.checkEmail(contact);
        Wrapper<InviteEntity> inviteEntityWrapper = new EntityWrapper<InviteEntity>()
                .eq("from_user", formUser)
                .eq("team_id", tId);
        //判断当前用户是否是登录状态
        if (isPhone) {
            Wrapper<MemberUserEntity> mobile = ew.eq("mobile", contact);
            memberUserEntity = memberUserService.selectOne(mobile);
            inviteEntityWrapper.eq("to_user_contact", contact);
        } else if (isEmail) {
            Wrapper<MemberUserEntity> email = ew.eq("email", contact);
            memberUserEntity = memberUserService.selectOne(email);
            inviteEntityWrapper.eq("to_user",contact);
        } else {
            return R.error(9, "联系方式异常");
        }
        InviteEntity inviteEntity = null;
        //说明此时用户已经注册过了，可以加入该项目团队
        if (!Objects.isNull(memberUserEntity)) {
            Long userId = memberUserEntity.getUserId();
            //确认是那个邀请人的
            // 判断地址是邀请的人还是直接登录的人
            if (!StringUtils.contains(formUser, "undefined")) {

                //在这里，将邀请人的团队id传入，将其邀请的对应状态修改
                inviteEntity = selectOne(inviteEntityWrapper);
                if (!Objects.isNull(inviteEntity)) {
                    //更新邀请状态
                    InviteEntity inviteE = selectById(iId);
                    inviteE.setIsOperate(type);
                    updateById(inviteE);

                    Long teamId = inviteEntity.getTeamId();
                    TeamEntity teamEntity = teamService.selectById(inviteEntity.getTeamId());
                    teamEntity.setCreateTime(DateTime.now().toDate());
                    teamEntity.setMemberId(memberUserEntity.getUserId());
                    if (type.equals(1)) {
                        //判读是否重复加入该项目
                        List<TeamEntity> teamList = teamService.selectList(new EntityWrapper<TeamEntity>()
                                .eq("member_id", userId)
                                .eq("bus_team_id", teamId)
                                .eq("member_exist",0));
                        for (TeamEntity t : teamList) {
                            Long projectId = t.getProjectId();
                            Long memberId = t.getMemberId();
                            if (memberId.equals(userId)) {
                                //删除邀请记录
                                deleteById(inviteEntity.getId());
                                return R.error(EnumToKeyUtil.toInt(Code.UPDATE_FAIL), "不能重复加入该项目");
                            }
                        }
                        teamEntity.setConfirm(1);
                        String fromUser = inviteEntity.getFromUser();
                        EntityWrapper<MemberUserEntity> entityEntityWrapper = new EntityWrapper<>();
                        boolean phoneExist = CheckUtil.checkEmail(fromUser);
                        boolean emailExist = CheckUtil.checkPhone(fromUser);
                        if (phoneExist) {
                            entityEntityWrapper.eq("email", fromUser);
                        } else if (emailExist) {
                            entityEntityWrapper.eq("mobile", fromUser);
                        }
                        //邀请人的用户实体
                        MemberUserEntity memberUserEntity1 = memberUserService.selectOne(entityEntityWrapper);
                        memberUserEntity.setCompanyId(memberUserEntity1.getCompanyId());
                        memberUserEntity.setUpdateTime(DateTime.now().toDate());
                        memberUserService.updateById(memberUserEntity);
                        teamEntity.setId(null);
                        teamService.insert(teamEntity);

                        //创建时间模板
                        //新建事件管理模板  后期整合代码
                        boolean flag = false;
                        Long pId = teamEntity.getProjectId();
                        EventManagementEntity eventManagement = null;
                        for (EventEnum e : EventEnum.values()) {
                            String desc = e.desc();
                            if (!flag) {
                                flag = true;
                                eventManagement = new EventManagementEntity();
                                eventManagement.setTitle(desc);
                                continue;
                            }
                            if (flag) {
                                flag = false;
                                eventManagement.setColor(desc);
                                eventManagement.setCreateTime(DateTime.now().toDate());
                                eventManagement.setMemberId(memberUserEntity.getUserId());
                                eventManagement.setProjectId(pId);
                                eventService.insert(eventManagement);
                            }
                        }
                        return R.ok("用户加入成功").put("code",HttpStatus.SC_EXPECTATION_FAILED).put("projectId",pId);
                    } else if (type.equals(2)) {
                        EntityWrapper<MemberUserEntity> entityEntityWrapper = new EntityWrapper<>();
                        boolean b = CheckUtil.checkEmail(formUser);
                        boolean b1 = CheckUtil.checkPhone(formUser);
                        if (b) {
                            entityEntityWrapper.eq("email", formUser);
                        } else if (b1) {
                            entityEntityWrapper.eq("mobile", formUser);
                        }
                        //邀请人的用户实体
                        MemberUserEntity formUserEntity = memberUserService.selectOne(entityEntityWrapper);
                        if(!Objects.isNull(formUserEntity)){
                            //拒绝邀请
                            return R.ok("用户拒绝成功")
                                    .put("code",HttpStatus.SC_CONTINUE)
                                    .put("userId",formUserEntity.getUserId())
                                    .put("projectId",teamEntity.getProjectId());
                        }else{
                            return R.ok("用户拒绝成功,无法获取邀请人信息")
                                    .put("code",HttpStatus.SC_CONTINUE)
                                    .put("userId",0)
                                    .put("projectId",teamEntity.getProjectId());
                        }
                    }else if(type.equals(0)){
                        return R.ok("您未回应该邀请");
                    }
                }
            }else{
                return R.ok("正常登录").put("code", 555);
            }
            return R.ok("操作成功");
        } else {
            return R.error(EnumToKeyUtil.toInt(Code.APPEND_DATA_ERROR), "用户不存在，请先注册");
        }

    }

    @Override
    public R enterInviteList(JoinInvitesReq joinInvitesReq) {
        String contact = joinInvitesReq.getContact();
        String formUser = joinInvitesReq.getFormUser();
        Long teamId = joinInvitesReq.getTeamId();
        Integer type = joinInvitesReq.getType();
        Long iId = joinInvitesReq.getIId();
        return enterInvite(contact, type, formUser, teamId,iId);
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

